﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.Xml;
using System.IO;

namespace WoSai.Base.Common
{
    public class SerializationHelper
    {
        private SerializationHelper()
        { }
        private static Dictionary<int, XmlSerializer> serializerDict = new Dictionary<int, XmlSerializer>();
        public static XmlSerializer GetSerializer(Type type)
        {
            int typeHash = type.GetHashCode();
            if (!serializerDict.ContainsKey(typeHash))
            {
                serializerDict.Add(typeHash, new XmlSerializer(type));
            }
            return serializerDict[typeHash];
        }

        public static object Load(string filename, Type type)
        {
            FileStream fs = null;
            try
            {
                fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                XmlSerializer serializer = new XmlSerializer(type);
                return serializer.Deserialize(fs);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (fs != null) { fs.Close(); }
            }
        }
        public static bool Save(object obj, string filename)
        {
            bool success = false;
            FileStream fs = null;
            try
            {
                fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
                XmlSerializer serializer = new XmlSerializer(obj.GetType());
                serializer.Serialize(fs, obj);
                success = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (fs != null)
                    fs.Close();
            }
            return success;
        }
    }
}
